import React, { useEffect, useState } from 'react'
import { Table, Tag, Image, Card, Alert, Button, Input, message } from 'antd'
import { SearchOutlined, RobotOutlined, RedoOutlined } from '@ant-design/icons'
import { PlayerInfoContainer } from './style'
import {
  getDataByPuuid,
  getDataByName,
  getGamesInfo,
  getDataByNameId,
  getCurrentSummonerRankInfo
} from '../../../utils/service'
import { heroList } from '../SearchTable/components/hero_list'
import {
  WARINGTIP,
  WARINGTEXT,
  INSERT_PIC,
  FILTER_KDA,
  FIND_TEAM,
  TIMES_TO_DATE,
  QUERY_GAME_TYPE,
  FILTER_MY_TEAM,
  FILTER_WIN_FAIL,
  SPLIT_ALL_TEAM,
  FILTER_TEAM_DATA,
  FIND_MAX_KILLS,
  FLITER_HERO,
  FILTER_HERO_NAME_DATA,
  GET_LAST_MY_HERO_NAME,
  GET_TIER,
  GET_TIER_TEXT,
  KDA_COLOR,
  GET_TAG_COLOR
} from './contants'
import { FILTER_HERO_NAME } from '../SearchTable/components/GameInfo/contants'
import GameInfo from './components/GameInfo'

interface Item {
  participantId: number
  championId: number
  stats: {
    kills: number
    deaths: number
    assists: number
  }
}

const TIPSTYLES: React.CSSProperties = {
  marginBottom: '20px'
}

const SearchTableContainer: React.CSSProperties = {
  maxWidth: '400px',
  display: 'flex',
  justifyContent: 'space-between',
  width: '100%',
  height: '100%',
  margin: '30px 0 30px 0'
}

const TierImage: React.CSSProperties = {
  zIndex: 1000,
  position: 'absolute',
  top: '50px',
  left: '13px'
}

const SearchTable: React.FC = () => {
  const [data, setData] = useState([])
  const [userPic, setUserPic] = useState('https://tva1.sinaimg.cn/bmiddle/006BkP2Hly1fwkdjro0rnj30ba06zglu.jpg')
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isRecord, setIsRecord] = useState({})
  const [playerName, setPlayerName] = useState('')
  const [loading, setLoading] = useState(true)
  const [sendDataLoading, setSendDataLoading] = useState(false)

  const COLUMNS: any = [
    {
      title: 'Time',
      dataIndex: 'gameCreationDate',
      key: 'gameCreationDate',
      align: 'center',
      render: (_: any, record: any) => <Tag>{TIMES_TO_DATE(record.gameCreationDate)}</Tag>
    },
    {
      title: '对局版本',
      dataIndex: 'gameVersion',
      key: 'gameVersion',
      align: 'center'
    },
    {
      title: '对局模式',
      dataIndex: 'gameMode',
      key: 'gameMode',
      align: 'center',
      render: (_: any, record: any) => <Tag>{QUERY_GAME_TYPE(record.queueId)}</Tag>
    },
    {
      title: '本局Team战绩',
      dataIndex: 'win',
      key: 'win',
      align: 'center',
      render: (_: any, record: any) => (
        <>
          <Tag color={FIND_TEAM(record.participants, record.teams)?.win === 'Fail' ? 'red' : 'blue'}>
            {FIND_TEAM(record.participants, record.teams)?.win === 'Fail' ? '失败' : '胜利'}
          </Tag>
        </>
      )
    },
    {
      title: 'K/D/A',
      dataIndex: 'kda',
      key: 'kda',
      align: 'center',
      render: (_: any, record: any) => (
        <>
          <Tag>
            {record.participants[0].stats.kills} / {record.participants[0].stats.deaths} /
            {record.participants[0].stats.assists}
          </Tag>
        </>
      )
    },
    {
      title: '本场赛马',
      dataIndex: 'chanceOfWin',
      key: 'chanceOfWin',
      align: 'center',
      render: (_: any, record: any) => (
        <>
          <Tag color={GET_TAG_COLOR(FILTER_KDA(record.participants) as keyof typeof KDA_COLOR)}>
            {FILTER_KDA(record.participants)}
          </Tag>
        </>
      )
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      align: 'center',
      render: (_: any, record: any) => (
        <Button type="link" onClick={handleClick(record)}>
          对局信息
        </Button>
      )
    }
  ]

  let playerData = JSON.parse(localStorage.getItem('playerData')!)

  const searchPlayer = async () => {
    if (!playerName) return
    await getDataByName({ name: playerName })
      .then(async (res: any) => {
        if (res && res.data) {
          localStorage.setItem('playerData', JSON.stringify(res.data))
          localStorage.setItem('puuid', JSON.stringify(res.data.puuid))
        }
      })
      .catch((error: Error) => {
        message?.error('[玩家查询]: 查询失败(可能未启动LOL客户端)')
      })

    playerData = JSON.parse(localStorage.getItem('playerData')!)
    const updatedPlayerData = JSON.parse(localStorage.getItem('playerData')!)
    if (localStorage.getItem('playerData')) {
      await setUserPic(INSERT_PIC(updatedPlayerData?.profileIconId) as string)
      await getSummonerByPuuid()
    } else {
      // 这里修改为查询失败，因为playerData未获取肯定客户端未启动或不是Admin启动项目
      message?.error('[玩家查询]: 查询失败(可能未启动LOL客户端)')
    }
  }

  const handleClick = (record: any) => (): void => {
    setIsRecord(record)
    handleModalOpen()
  }

  const handleModalOpen = () => {
    setIsModalOpen(!isModalOpen)
  }

  const sendData = () => {
    getSummonerByPuuid(true)
  }

  const getSummonerByPuuid = async (search: boolean = false) => {
    if (search) {
      setSendDataLoading(true)
      try {
        const puuidString = localStorage.getItem('puuid')!
        const puuid = JSON.parse(puuidString)
        const timestamp = Date.now()
        const res = await getDataByPuuid({ puuid, timestamp })
        if (res && res.data && res.data.games && res.data.games.games.length > 0) {
          const myTeamList = await FILTER_MY_TEAM(res)
          const winFailList = await FILTER_WIN_FAIL(myTeamList)
          // 获取最近一把对局数据
          const lastGame = await getGamesInfo({
            gameId: res.data.games.games[0].gameId
          })
          // 获取本局游戏的召唤师数据
          let team_one_list = lastGame.data.participantIdentities.splice(0, 5)
          let team_two_list = lastGame.data.participantIdentities
          let myTeam: any = []
          const summonerList = [...team_one_list, ...team_two_list]
          const playerDataString = localStorage.getItem('playerData')
          const playerData = playerDataString ? JSON.parse(playerDataString) : null
          const summonerName = playerData?.displayName
          const team_personal = summonerList.filter((item: any) => {
            if (item.player.summonerName === summonerName) {
              return item
            }
          })
          const player = team_one_list.find(
            (item: any) => item.player.summonerName === team_personal[0].player.summonerName
          )
          if (player) {
            myTeam = [...team_one_list]
          } else {
            myTeam = [...team_two_list]
          }
          // 获取我方队伍使用的英雄数据
          let team_one_data: any[] = lastGame.data.participants.splice(0, 5)
          let team_two_data: any[] = lastGame.data.participants
          let updatedTeamOne: any[] = []
          let updatedTeamTwo: any[] = []
          let allTeam = [...team_one_data, ...team_two_data]
          team_one_data.map((item: any) => {
            const hero = FILTER_HERO_NAME(item.championId, heroList)
            updatedTeamOne = [...updatedTeamOne, hero]
          })
          team_two_data.map((item: any) => {
            const hero = FILTER_HERO_NAME(item.championId, heroList)
            updatedTeamTwo = [...updatedTeamTwo, hero]
          })
          // 先找出我
          const me = myTeam.filter((item: any) => {
            return item.player.summonerName === summonerName
          })
          // 再根据我找出我的队伍stats
          const me_team = await SPLIT_ALL_TEAM(allTeam, me)
          // 筛选出我方队伍使用的英雄列表
          const filteredResult = FILTER_TEAM_DATA({
            meTeam: me_team[0],
            oneTeam: updatedTeamOne,
            twoTeam: updatedTeamTwo
          })
          // 根据teamId判断队伍
          const teamId = res.data.games.games[0].participants[0].teamId
          let result = []
          if (teamId === 100) {
            result = team_one_data.slice()
          } else if (teamId === 200) {
            result = team_two_data.slice()
          }
          // 找出我方team击杀最多的MVP
          const maxKills: Item = FIND_MAX_KILLS(result)
          // 获取我方MVP数据
          const MVP = FLITER_HERO(maxKills.participantId, summonerList)
          // 获取我方MVP英雄数据
          const MVP_HERO = FILTER_HERO_NAME_DATA(maxKills.championId, filteredResult)
          message.success(`查询如下: ${summonerName}
           | 近20场(${winFailList[0]}胜/${winFailList[1]}负)
            | 最近对局: ${QUERY_GAME_TYPE(res.data.games.games[0].queueId)}
            	| 本局Team战绩: ${myTeamList[0].win === 'Win' ? '胜利' : '失败'}
               | KDA: ${res.data.games.games[0].participants[0].stats.kills}
                / ${res.data.games.games[0].participants[0].stats.deaths}
                 / ${res.data.games.games[0].participants[0].stats.assists}
                  | 本场赛马: ${FILTER_KDA(res.data.games.games[0].participants[0])}
                   | 使用英雄: ${GET_LAST_MY_HERO_NAME(res.data.games.games[0].participants[0].championId, filteredResult)[0].name
            }
                    | 我方MVP: ${MVP[0].player.summonerName}(${MVP_HERO[0].name})
                     | 对局版本: ${lastGame.data.gameVersion}
                      | 工具作者: 星光菌子 #12668
                       |
                       `)
          setSendDataLoading(false)
        } else {
          message.error('请检查客户端启动状态 | 检查您的网络 | 刷新页面重试')
          setSendDataLoading(false)
        }
      } catch (error: unknown) {
        setSendDataLoading(false)
        return message?.error('[数据概览]: 数据生成失败(可能未启动LOL客户端)')
      }
    } else {
      setLoading(true)
      const puuidString = localStorage.getItem('puuid')
      if (puuidString) {
        try {
          const puuid = JSON.parse(puuidString)
          const timestamp = Date.now()
          const res = await getDataByPuuid({ puuid, timestamp })
          if (res && res.data && res.data.games && res.data.games.games) {
            setData(res.data.games.games)
            setLoading(false)
          } else {
            setData([])
            setLoading(false)
          }
        } catch (error) {
          // 查询接口报错是因为有的玩家是别的区服的，所以当前API不能跨区查询，等找找API
          message.warning('[未查询到该玩家]: 召唤师ID输入错误 | 暂不支持跨区查询')
          await setUserPic('https://tva1.sinaimg.cn/bmiddle/006BkP2Hly1fwkdjro0rnj30ba06zglu.jpg' as string)
          setData([])
        }
      } else {
        console.error('未查询到本地PUUID, 请确定已登录英雄联盟客户端')
        setData([])
      }
    }
  }

  // requestIdleCallback 
  // 并不是所有浏览器都支持的标准方法
  // 为了兼容性，请确保在使用前先检查浏览器是否支持该方法, 建议使用Google浏览器
  useEffect(() => {
    const fetchData = async () => {
      try {
        await getSummonerByPuuid()
        if (localStorage.getItem('playerData') && JSON.parse(localStorage.getItem('playerData')!).profileIconId) {
          await setUserPic(INSERT_PIC(JSON.parse(localStorage.getItem('playerData')!).profileIconId) as string)
        }
      } catch (error) { }
    }
    const idleCallback =
      window.requestIdleCallback ||
      function (cb) {
        const start = Date.now()
        return setTimeout(function () {
          cb({
            didTimeout: false,
            timeRemaining: function () {
              return Math.max(0, 50 - (Date.now() - start))
            }
          })
        }, 1)
      }
    const idleHandle = idleCallback(() => {
      fetchData()
    })
    return () => {
      window.cancelIdleCallback(idleHandle)
    }
  }, [])

  return (
    <div style={{ flex: 1, marginRight: '20px' }}>
      <PlayerInfoContainer>
        <Alert message={WARINGTIP} description={WARINGTEXT} style={TIPSTYLES} type="info" showIcon />
        <div style={SearchTableContainer}>
          <Input
            allowClear
            value={playerName}
            onChange={e => setPlayerName(e.target.value)}
            placeholder="仅可查询同区 | 召唤师名称 #编号"
          />
          <Button onClick={searchPlayer} style={{ marginLeft: '10px' }} type="primary" icon={<SearchOutlined />}>
            查询
          </Button>
        </div>
        <Card>
          <div className="user-info">
            <div className="user-pic">
              {localStorage.getItem('currentSummonerRankInfo') &&
                JSON.parse(localStorage.getItem('init_name')!) === playerData?.displayName ? (
                <img
                  style={TierImage}
                  width={100}
                  src={GET_TIER(JSON.parse(localStorage.getItem('currentSummonerRankInfo')!).tier)}
                />
              ) : null}
              <Image preview={false} style={{ borderRadius: '50%' }} width={80} height={80} src={userPic} />
            </div>
            <div className="user-data">
              <span className="row-txt">
                {playerData?.displayName === '星光菌子' ? (
                  <span className="row-tip">欢迎软件作者:</span>
                ) : (
                  <span className="row-tip">查询用户:</span>
                )}
                <Tag bordered={false} color="processing">
                  {playerData?.displayName || '无'}
                </Tag>
                ，<span className="row-tip">当前等级:</span>
                <Tag bordered={false} color="processing">
                  {playerData?.summonerLevel || '无'}
                </Tag>
                <span className="row-tip">升至下一级需要:</span>
                <Tag bordered={false} color="processing">
                  {playerData?.xpUntilNextLevel - playerData?.xpSinceLastLevel || '无'}
                </Tag>
                <span className="row-tip">经验</span>
                <span className="row-tip">段位:</span>
                <Tag
                  bordered={false}
                  color="processing"
                  style={{
                    color: GET_TIER_TEXT(JSON.parse(localStorage.getItem('currentSummonerRankInfo')!)?.tier).color,
                    backgroundColor: '#e6f4ff'
                  }}
                >
                  <span style={{ display: 'flex', alignItems: 'center' }}>
                    {GET_TIER_TEXT(JSON.parse(localStorage.getItem('currentSummonerRankInfo')!)?.tier).text}
                    {JSON.parse(localStorage.getItem('currentSummonerRankInfo')!)?.division || ''}
                    <Image
                      preview={false}
                      style={{ borderRadius: '50%', lineHeight: '0px' }}
                      width={20}
                      height={20}
                      src={GET_TIER(JSON.parse(localStorage.getItem('currentSummonerRankInfo')!)?.tier)}
                    />
                  </span>
                </Tag>
              </span>
              <span className="row-txt">
                <span className="row-tip">召唤师战绩查询权限：</span>
                <Tag bordered={false} color={playerData?.privacy === 'PUBLIC' ? 'processing' : 'red'}>
                  {playerData?.privacy === 'PUBLIC' ? '公开' : '隐藏'}
                </Tag>
              </span>
              <span className="row-txt">
                <Button
                  className="b-btn"
                  type="default"
                  loading={sendDataLoading}
                  onClick={sendData}
                  icon={<RobotOutlined />}
                >
                  生成数据概览
                </Button>
                <Button
                  type="default"
                  onClick={() => {
                    window.location.reload()
                  }}
                  icon={<RedoOutlined />}
                >
                  刷新
                </Button>
              </span>
            </div>
          </div>
        </Card>
      </PlayerInfoContainer>
      <Table
        rowKey={(record: any) => record.gameId}
        loading={loading}
        columns={COLUMNS}
        dataSource={data || []}
        pagination={{ pageSize: 10 }}
      />
      <GameInfo isModalOpen={isModalOpen} handleModalOpen={handleModalOpen} record={isRecord} />
    </div>
  )
}

export default SearchTable
